package main

import (
	"flag"
	"fmt"
	log "github.com/cihub/seelog"
	"github.com/gin-gonic/gin"
	_ "github.com/jinzhu/gorm/dialects/mysql" //驱动包
	"html/template"
	"net/http"
	"os"
	"path/filepath"
	"strings"
	"test/controllers"
	"test/helpers"
	"test/models"
	"test/system"
	//_ "github.com/jinzhu/gorm/dialects/sqlite"
)

func main() {

	configFilePath := flag.String("C", "conf/conf.yaml", "config file path")
	flag.Parse()

	log.Info("main.go---打印Log ")
	if err := system.LoadConfiguration(*configFilePath); err != nil {
		log.Critical("err parsing config log file", err)
		return
	}

	db, err := models.InitDB()
	if err != nil {
		//seelog.Critical("err open databases", err)
		return
	}
	defer db.Close()

	/*db, _ := gorm.Open("sqlite3", "./gorm.db")
	defer db.Close()*/

	/*db, err := gorm.Open("mysql",
		"root:123456@/test?charset=utf8&parseTime=True&loc=Local")

	if err != nil {
		fmt.Println(err)
		return
	}else {
		fmt.Println("connection succedssed")
	}
	defer db.Close()*/

	r := gin.Default()

	setTemplate(r)

	//r.LoadHTMLGlob("templates/*")
	//r.LoadHTMLGlob("./views/**/*")
	//r.Static("/static", filepath.Join(getCurrentDirectory(), "./static"))
	r.Static("/static", "./static")

	//路由
	/*r.GET("/", func(c *gin.Context) {
		c.HTML(http.StatusOK, "index.tmpl", gin.H{
			"title": "Welcome GO GIN",
		})
	})*/

	r.NoRoute(controllers.Handle404)
	r.GET("/", controllers.IndexGet)
	r.GET("/index", controllers.IndexGet)
	r.GET("/post/:id", controllers.PostGet)

	r.GET("/test", controllers.IndexJson)
	r.GET("/home", controllers.Test)
	r.GET("/json2", func(c *gin.Context) {
		c.JSON(http.StatusNotFound, gin.H{
			"status": 1,
			//"dat": []string,
			"msg": "error",
		})
	})

	/*r.GET("/test", func(c *gin.Context) {
		c.String(http.StatusOK, "Hello world")
	})
	r.GET("/ping", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message": "pong",
		})

	})*/

	r.POST("/form", func(c *gin.Context) {
		type1 := c.DefaultPostForm("type", "alert")
		username := c.PostForm("username")
		pwd := c.PostForm("password")
		c.String(http.StatusOK, fmt.Sprintf("type is %s, username is %s, password is %s", type1, username, pwd))
	})

	//最后
	r.Run(":8088") // 监听并在 0.0.0.0:8080 上启动服务
	//http.ListenAndServe(":8088", r)
}

func getCurrentDirectory() string {
	dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
	if err != nil {
		log.Critical(err)
	}
	return strings.Replace(dir, "\\", "/", -1)
}

func setTemplate(engine *gin.Engine) {

	funcMap := template.FuncMap{
		"dateFormat": helpers.DateFormat,
		"substring":  helpers.Substring,
		"isOdd":      helpers.IsOdd,
		"isEven":     helpers.IsEven,
		//"truncate":   helpers.Truncate,
		"add":   helpers.Add,
		"minus": helpers.Minus,
		//"listtag":    helpers.ListTag,
	}

	engine.SetFuncMap(funcMap)
	engine.LoadHTMLGlob("./views/**/*")

}
